﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using ProgNetComponents.Data.SqlCe;
using ProgNetComponentsDx.Options;

namespace Wydatki.Zakupy
{
    public partial class FormZakupy : MyBaseSqlCeGridForm
    {
        string defLoadTime = "";
        bool firstLoad = true;

        public FormZakupy()
        {
            InitializeComponent();
            gvChild.OptionsView.ShowFooter = true;
            
            defLoadTime = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Wydatki.DefLoadTime);
            DateTime ds = DateTime.Now;
            DateTime de = DateTime.Now;
            switch (defLoadTime)
            {
                case WydatkiGlobals.WydatkiDefOpenType.Miesiac:
                case WydatkiGlobals.WydatkiDefOpenType.Nic:
                    ds = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    de = ds.AddMonths(1).AddDays(-1).DayEnd();
                    break;
                case WydatkiGlobals.WydatkiDefOpenType.Ostatnie30Dni:
                   ds = DateTime.Now.DayStart().AddDays(-30);
                    de = DateTime.Now.DayStart();
                    break;
                case WydatkiGlobals.WydatkiDefOpenType.Tydzien:
                    ds = DateTime.Now.DayStart().AddDays(-7);
                    de = DateTime.Now.DayStart();
                    break;
            }
            editDo.EditValue = de;
            editOd.EditValue = ds;

            manager.AddTableDef(produkty.STP_PRODUKTY);
            manager.AddTableDef(produkty.STP_PROD_KAT);
            Setup.Tools.ProduktMatch.ProductMatched += new Setup.Tools.ProduktMatch.ProductMatchHandler(ProduktMatch_ProductMatched);
        }
        ~FormZakupy()
        {
            Setup.Tools.ProduktMatch.ProductMatched -= new Setup.Tools.ProduktMatch.ProductMatchHandler(ProduktMatch_ProductMatched);
        }
        void ProduktMatch_ProductMatched(Setup.Tools.ProduktMatch.ProductMatchEventArgs e)
        {
            DataRow[] rows =  this.zakupyDataSet.WRK_WYDATKI_PRODUKTY.Select("WRK_WYD_PROD_PRODUKT = " + e.OldProduct);
            bool delete =false;
            bool modified = false;

            Dictionary<string, object> curValues = new Dictionary<string, object>();
            foreach (DataRow r in rows)
            {
                curValues.Clear();
                if (r.RowState != DataRowState.Deleted)
                {
                    foreach (DataColumn c in r.Table.Columns)
                    {
                        if (!c.ReadOnly && c.ColumnName != "WRK_WYD_PROD_PRODUKT")
                            curValues.Add(c.ColumnName, r[c]);
                    }
                }
                else
                {
                    delete = true;
                }
                modified = r.RowState == DataRowState.Modified;
                if(r.RowState!= DataRowState.Added && r.RowState != DataRowState.Detached)
                    r.RejectChanges();
                r["WRK_WYD_PROD_PRODUKT"] = e.NewProduct;

                if (r.RowState != DataRowState.Added && r.RowState != DataRowState.Detached)
                    r.AcceptChanges();
                if (modified)
                    r.SetModified();

                foreach (KeyValuePair<string, object> kvp in curValues)
                {
                    r.SetColVal(kvp.Key, kvp.Value);
                }
                if (delete)
                    r.Delete();
            }
        }
        protected override bool GetRecords()
        {
            selectDataProvider1.GetSettings(this).Parameters["DATA_OD"].Value = editOd.DateTime.DayStart();
            selectDataProvider1.GetSettings(this).Parameters["DATA_DO"].Value = editDo.DateTime.DayEnd();

            bool res = true;
            if (!firstLoad || defLoadTime != WydatkiGlobals.WydatkiDefOpenType.Nic)
                res = base.GetRecords();
            firstLoad = false;
            RefreshSuma();
            return res;
        }
        private SqlCeDataManager manager = new SqlCeDataManager();
        private Setup.DataSets.ProduktyDataSet produkty = new Setup.DataSets.ProduktyDataSet();
        private Wydatki.Setup.DataSets.SklepyDataSet sklepy = new Setup.DataSets.SklepyDataSet();

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            FinishEdit();
            if (editDo.EditValue.IsNotNull() &&
                    editOd.EditValue.IsNotNull())
            {
                if (modeProvider1.CurrentMode == ProgNetComponentsDx.Enums.FormMode.Edit)
                {
                    if (changeDetectorProvider1.HasChanges)
                    {
                        SaveClick();
                    }
                }
                
                if (!changeDetectorProvider1.HasChanges)
                {
                    GetRecords();
                }
            }
        }
        decimal sum;

        private void gvChild_CustomSummaryCalculate(object sender, DevExpress.Data.CustomSummaryEventArgs e)
        {
            if (e.SummaryProcess == DevExpress.Data.CustomSummaryProcess.Start)
            {
                sum = 0;
            }
            else if (e.SummaryProcess == DevExpress.Data.CustomSummaryProcess.Calculate)
            {
                DataRow r = (sender as GridView).GetDataRow(e.RowHandle);
                if (r != null)
                {
                    sum += r["WRK_WYD_PROD_ILOSC"].AsDecimal() * r["WRK_WYD_PROD_CENA_JEDNOSTKOWA"].AsDecimal();
                }
            }
            else if (e.SummaryProcess == DevExpress.Data.CustomSummaryProcess.Finalize)
            {
                e.TotalValue = sum;
            }
        }
        private void RefreshSuma()
        {
            DataRow[] rows = zakupyDataSet.WRK_WYDATKI_PRODUKTY.Select();
            decimal sum = 0;
            foreach (DataRow r in rows)
            {
                if (r.CanRead())
                {
                    sum += decimal.Round(r["WRK_WYD_PROD_ILOSC"].AsDecimal() * r["WRK_WYD_PROD_CENA_JEDNOSTKOWA"].AsDecimal(), 2);
                }
            }
            teSuma.EditValue = sum;
        }
        private void btnSumeRefresh_Click(object sender, EventArgs e)
        {
            RefreshSuma();
        }
        protected override bool Save()
        {
            bool res = true;
            bool showProductDlg = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Wydatki.NewProdDlg);

            if (!Tools.WydatkiTools.ProcessNewProducts(zakupyDataSet, produkty, sklepy, showProductDlg))
            {
                this.ShowDxErrorDialog("Błąd dodawania produktów/sklepów");
                res = false;
            }
            if (res)
            {
                res &= base.Save();
                RefreshSuma();
            }
            return res;
        }
        protected override void OnContextChanged()
        {
            base.OnContextChanged();
            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Wydatki.AutoRefreshSuma))
                RefreshSuma();
        }

        private void bbiDodaj_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FormDodajZakupy f = new FormDodajZakupy(zakupyDataSet, sklepy, produkty);
            f.Added += new EventHandler(f_Added);
            f.ShowDialog();
        }

        void f_Added(object sender, EventArgs e)
        {
            OnContextChanged();
        }

        private void repItemProdukt_Settings_CreateNewRow(object sender, ProgNetComponentsDx.Browsers.CreateNewRowEventArgs e)
        {
            DataRow row = produkty.STP_PRODUKTY.NewRow();
            row["STP_PROD_NAZWA"] = e.DisplayValue;
            produkty.STP_PRODUKTY.Rows.Add(row);
            e.NewRow.Assign(row);
            
        }

        private void repItemSklep_Settings_CreateNewRow(object sender, ProgNetComponentsDx.Browsers.CreateNewRowEventArgs e)
        {
            DataRow row = sklepy.STP_SKLEPY.NewRow();
            row["STP_SKL_NAZWA"] = e.DisplayValue;
            sklepy.STP_SKLEPY.Rows.Add(row);
            e.NewRow.Assign(row);
        }
    }
}
